package net.lastcoder.ifserver.session;

import net.lastcoder.ifserver.util.TextUtils;

import java.io.Serializable;

/**在ifserver服务器中，地址是通过[username]/[resource]来索引的，resource为一个字符，已经默认了4个resource，
 * 足所有的现阶段所有情况，resource有：{@link #RESOURCE_SERVER}、{@link #RESOURCE_USER}、
 * {@link #RESOURCE_ROOM}、{@link #RESOURCE_ZONE}<br>
 * auth: WenYF
 * date: 2016/9/29
 */
public class UlaID implements Serializable {
    /**
     * 服务器标识
     */
    public static final char RESOURCE_SERVER = '0';
    /**
     * 用户标识
     */
    public static final char RESOURCE_USER = '1';
    /**
     * 房间标识
     */
    public static final char RESOURCE_ROOM = '2';
    /**
     * 区间标识
     */
    public static final char RESOURCE_ZONE = '3';

    public UlaID(String username, char resource) {
        this.username = username;
        this.resource = resource;
    }

    public UlaID(String username, String resource) {
        this.username = username;
        this.resource = resource.charAt(0);
    }



    private String username;
    private char resource;

    /**
     * @param username 设置username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @param resource 设置resource
     */
    public void setResource(char resource) {
        this.resource = resource;
    }


    /**
     * @return 得到用户名
     */
    public String getUsername() {
        return username;
    }


    /**
     * @return 得到resource
     */
    public char getResource() {
        return resource;
    }

    /**
     * @return 把地址转为字符串
     */
    public String toAddress() {
        if (resource < RESOURCE_SERVER) {
            return username;
        } else {
            return username + "/" + resource;
        }
    }

    /**从一个字符串中构造出地址，必须要满足"xx/x"的格式
     * @param str
     * @return
     * @throws IllegalArgumentException
     */
    public static UlaID fromAddress(String str) throws IllegalArgumentException {
        if (TextUtils.isEmpty(str)) {
            return null;
        }

        if (str.contains("/")) {
            String[] splits = str.split("/");
            return new UlaID(splits[0], splits[1]);
        } else {
            throw new IllegalArgumentException("not take char '/'");
        }
    }

    @Override
    public String toString() {
        return "UlaID{" +
                "username='" + username + '\'' +
                ", resource=" + resource +
                '}';
    }
}
